package mysql

import (
	"gorm.io/gorm"
	"shopping/logger"
	"shopping/model"
)

// UserDao 结构体
type UserDao struct {
	db *gorm.DB
}

// NewUserDao 实例化
func NewUserDao(db *gorm.DB) *UserDao {
	return &UserDao{
		db: db,
	}
}

// Migration 生成表
func (userDao *UserDao) Migration() {
	err := userDao.db.AutoMigrate(&model.User{})
	if err != nil {
		logger.Log.Info(err.Error())
	}
}

// Create 创建用户
func (userDao *UserDao) Create(user *model.User) error {
	result := userDao.db.Create(user)
	return result.Error
}

// GetByName 根据用户名查询用户数据
func (userDao *UserDao) GetByName(name string) (model.User, error) {
	var resultUser model.User
	err := userDao.db.Where("Username = ?", name).Where("DelFlag = ?", 0).First(&resultUser).Error
	if err != nil {
		return model.User{}, err
	}
	return resultUser, nil
}

// update 更新用户
func (userDao *UserDao) Update(user *model.User) error {
	// save函数, 会根据主键来判断是执行更新还是插入, 如果数据存在会更新, 不存在会插入
	return userDao.db.Save(&user).Error
}

// InsertSampleData 添加测试数据
func (userDao *UserDao) InsertSampleData() {
	newUser := model.NewUser("admin", "admin", "admin")
	newUser.IsAdmin = true
	userDao.db.Where(model.User{Username: newUser.Username}).Attrs(
		model.User{Username: newUser.Username, Password: newUser.Password, Password2: newUser.Password2}).FirstOrCreate(&newUser)
	newUser = model.NewUser("user", "user", "user")
	newUser.IsAdmin = true
	userDao.db.Where(model.User{Username: newUser.Username}).Attrs(
		model.User{Username: newUser.Username, Password: newUser.Password, Password2: newUser.Password2}).FirstOrCreate(&newUser)
}
